# -*- coding:utf-8 -*-

from pydantic import BaseModel
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import text


from app.logger import getLogger
from core.database import get_db

logger = getLogger()


router = APIRouter(prefix="/database")

class Sql(BaseModel):
    sql: str

@router.post("/", response_model=list, summary="执行sql")
async def exec_sql(sql: Sql, session: Session=Depends(get_db)):
    sql = sql.sql
    if sql is None or len(sql) <= 0:
        logger.error(f'sql 为空: {sql}')
    results = []
    sqls = sql.split(';')
    cud = []
    retrieve = []
    for item in sqls:
        item = item.strip()
        if len(item) <= 0:
            continue
        if item.upper().startswith('SELECT'):
            retrieve.append(item)
        else:
            cud.append(item)
    for item in sqls:
        item = item.strip()
        if len(item) <= 0:
            continue
        try:
            ret = session.execute(text(f'{item};'))
            if item in retrieve:
                keys = ret.keys()
                ret = [dict((zip(keys, item)))
                        for item in ret.fetchall()]
                results.append({item: ret})
            else:
                results.append({item: 'SUCCESS'})
        except BaseException as e:
            results.append({item: f'Failed: {e}'})
    if len(cud) > 0:
        session.commit()
    return results
